// pages/count/count.js
const host = require('../../config').host
import {code} from '../../utils/result'
var requestYear = new Date().getFullYear()
var requestMonth = (("0" + (new Date().getMonth() + 1)).slice(-2))


Page({
  data: {
    listAll: [],
    listDay:[],
    listWeek: [],
    listCat: [],
    listInc: [],
    typeNumToStr:{
      0 : '支出',
      1: '收入'
    },
    optionColorId: 3,
    getBillTypeColor:{
        0: 'outcome-color',
        1: 'income-color'
    },
    getCategoryName:{
        0 : '餐饮',
        1 : '交通',
        2 : '健康',
        3 : '购物',
        4 : '娱乐',
        5 : '其他'
    },
  },

  getCountList(that,Requrl) {
    var that=this
    var userId = that.data.userInfo.userId;
    wx.request({
      url: host +"bill/"+ Requrl +"?userId=" + userId,
      method: "GET",
      success: function (res) {
        if (res.data.code == code.SUCCESS) {
          //根据不同类型处理数据
          if(Requrl == "today"){
            that.setData({
              listDay: res.data.data
            })
          }
          else if(Requrl == "week"){
            let data =res.data.data
            let tempList= [0,0,0,0,0,0]
            for (const key in data) {
              if (Object.hasOwnProperty.call(data, key)) {
                const element = data[key];
                tempList[element.category_id] += (element.type==0?-element.money:element.money)
              }
            }
            that.setData({
              listWeek : tempList
            })
          }
          else if(Requrl == "all"){
            let data =res.data.data
            let tempList= [0,0,0,0,0,0]
            for (const key in data) {
              if (Object.hasOwnProperty.call(data, key)) {
                const element = data[key];
                tempList[element.category_id] += (element.type==0?-element.money:element.money)
              }
            }
            that.setData({
              listAll : tempList
            })
          }
        }
        else {
          wx.showToast({
            title: '查询失败',
            image: "../../images/icon-no.png",
            mask: true,
            duration: 1000
          })
        }
      }
    })
  },
  outputReport(){
    let that = this
    let userId = that.data.userInfo.userId;
      wx.showModal({
        title: '导出账单报表',
        content: '将以excel格式导出报表，包含全部账单信息（账单详情，时间，金额为以及类型），确定导出吗',
        complete: (res) => {
          if (res.confirm) {
            wx.showLoading({
              title: '正在请求',
            })
            //请求创建文件
            wx.request({
              url: host + 'report/createReport?userId=' + userId ,
              method:'GET',
              success(res){
                if(res.data.code == code.FAILED){
                  wx.hideLoading();
                  wx.showToast({
                    title: '请求失败',
                    icon: 'error'
                  })
                }
                else{
                  //请求下载文件
                  wx.downloadFile({
                    url: host + 'report/getReport?userId=' + userId + '&'+"fileName="+res.data.data,
                    method:'GET',
                    success(res){
                      wx.hideLoading();
                      if(res.statusCode == '200'){
                        console.log(res.tempFilePath)
                        wx.getFileSystemManager().saveFile({
                          tempFilePath : res.tempFilePath,
                          success(res){
                            console.log(res)
                            wx.showToast({
                              title: '保存成功',
                            })
                            setTimeout(() => {
                              wx.openDocument({
                                filePath: res.savedFilePath,
                                showMenu: true,
                                fileType:'xls',
                              })
                            }, 500);
                            
                          },
                          fail(res){
                            wx.showToast({
                              title: '保存失败',
                              icon: 'error'
                            })
                          }
                        })
                      }
                    }
                  })
                }
              },
              fail(){
                wx.hideLoading()
                wx.showToast({
                  title: '请求失败',
                })
              }
            })
          }
        }
      })
  },
  onLoad: function () {
    var that = this
    //调用应用实例的方法获取全局数据
    var app = getApp()
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    })
  },
  onShow(){
    var that = this
    this.getCountList(that, "today")
  },
  //分类查看
  bindOptionTap: function (e) {
    var that = this
    if(e.target.id>3 || e.target.id <1)return
    that.setData({
      optionColorId: e.target.id
    })

    switch (e.target.id) {
      case '1':
        that.getCountList(that,"all")
        break;

      case '2':
        that.getCountList(that,"week")
        break;

      case '3':
        that.getCountList(that,"today");
        break;
    }
  },

  bindAll: function (e) {
    var that = this

    var param = e.currentTarget.dataset.id.split("-")

    switch (param.length) {
      case 1:
        requestYear = param[0]
        requestMonth = '00'
        // getCountList(that)

        that.setData({
          optionColorId: 2
        })
        break;

      case 2:
        requestYear = param[0]
        requestMonth = param[1]
        // getCountList(that)

        that.setData({
          optionColorId: 3
        })
        break;

      case 3:
        wx.navigateTo({
          
        })
        break;
    }
  },

  bindCat: function (e) {
    wx.navigateTo({
     
    })
  },

  
})